import React, { useState,useEffect } from "react";
import { useNavigate } from 'react-router-dom'
import SearchBox from '../../components/common/SearchBox'
import Loading from '../../components/common/loading'
import ListSearch from '../../components/ListSearch'
import { 
  Container,HeaderWrapper,GoodsWrapper,ListWrapper,Empty,EnterLoading 
} from "./style";
import nothing from '../../assets/nothing.jpg'
// 分仓库
import { connect } from "react-redux";
import { getSearch,changeEnterLoading } from "./store/actionCreators";


const Search = (props) =>{
  const navigate = useNavigate()
  const [query, setQuery] = useState('')
  const { enterLoading,search } = props
  const { getSearchDispatch,changeEnterLoadingDispatch } = props
  const handleQuery = (q) => {
    setQuery(q)
  }
  useEffect(() => {
    if (query.trim()) {
      getSearchDispatch(query),
      changeEnterLoadingDispatch(true)
    }
  }, [query])
const renderGoodsList = () => {
    return (
      <ListWrapper>
        <div className="container">
        {
          // 过滤筛选
          search.filter(item => 
            item.title.indexOf(query) != -1 || item.content.indexOf(query) != -1
          ).map(item => {
            return (
              <ListSearch key={item.id} things={item} />
            )
          })
        }
        </div>
      </ListWrapper>
    )
  }
// 如果没有搜索到则输出空
const EmptyWrapper = () => {
    return (
      <Empty>
          <img src={nothing} />
      </Empty>
    )
  }
return (
  <Container>
    <HeaderWrapper>
      {/* 头部搜索框 */}
        <SearchBox
          newQuery={query}
          handleQuery={handleQuery}>
          </SearchBox>
        <span onClick={() => navigate(-1)}>取消</span>
    </HeaderWrapper>
    {/* 商品搜索详情 */}
    <GoodsWrapper show={query}>
      {search.filter(
        item => item.title.indexOf(query) != -1||item.content.indexOf(query)!=-1
      ).length > 0 ? renderGoodsList() : EmptyWrapper()}
    </GoodsWrapper>
      { enterLoading && <EnterLoading><Loading></Loading></EnterLoading> }
    </Container>
    )  
 }

const mapStateToProps = (state) => {
  return {
    search: state.searchlist.search,
    enterLoading:state.searchlist.enterLoading
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    getSearchDispatch(query) {
      dispatch(getSearch(query))
    },
    changeEnterLoadingDispatch(data) {
      dispatch(changeEnterLoading(data))
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(React.memo(Search))